import React, { Component } from 'react'
import axios from 'axios';
import ETable from './../../components/ETable'
import Utils from '../../utils/utils';
import menoConfig from './../../config/menuConfig'
import {Card, Button, Form, Input, Select, Tree, Transfer, Modal, Table ,message} from 'antd'

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
export default class Permission extends Component {
    state={}
    componentWillMount() {
        this.requestList()
    }
    // onRowClick = (record, index) => {
    //     let selectKey=[index];
    //     this.setState({
    //         selectedRowKeys:selectKey,
    //         selectItem:record,
    //         selectInex:index
    //     })
    //     console.log(this.state.selectItem)
    // }
    handleRole = () => {
        this.setState({
            isRoleVisible:true
        })
    }
    handlePermission =() => {
        let item = this.state.selectedItem
        if(!item) {
            Modal.info({
                title:"请选择一个角色"
            })
            return false
        }
        this.setState({
            isPersVisible:true,
            detailInfo:item,
            menuInfo:item.menu
        })
    }
    handlePersSubmit= () => {
        let data = this.roleForm.props.form.getFieldsValue();
        //console.log(data)
       // console.log( this.state.selectedItem)
        //获取当前表单的值
        data.role_id = this.state.selectedItem.id;
        //给对应的id改变权限
        data.menu = this.state.menuInfo;
        //把添加的新的权限传过去
        axios.get('https://www.studyinghome.com/mock/5e4ca5d80167590746b7615d/example/perss',{
            params: {  
               ...data
             }
        })
        .then((res) => {
            this.setState({
                dataSource:res.data.list,
                isPersVisible:false
            })
        })
        this.requestList()
    }
    handleUserSubmit = () => {

    }
    handleRoleSubmit = () => {
        let data = this.roleForm.props.form.getFieldsValue()
        if(data.role_name==undefined || data.state==undefined) {
            Modal.info({
                title:"请输入内容"
            })
            return;
        }
        this.roleForm.props.form.resetFields();
        message.success("创建成功")
        this.setState({
            isRoleVisible:false
        })
        this.requestList()
    }
    //用户授权
    handleUserAuth=() => {
        let item = this.state.selectedItem;
        if(!item) {
            Modal.info({
                title:"请选择一个用户"
            })
            return;
        }
        this.getRoleUserList(item.id)
    }
    getRoleUserList = (id) => {
        let item = this.state.selectedItem;
        axios.get("https://www.studyinghome.com/mock/5e4ca5d80167590746b7615d/example/user_list")
        .then((res) => {
           if(res) {
               this.setState({
                   isUserVisible:true,
                   detailInfo:item
               })
            this.getAuthUserList(res.data.list);
           }
        })
    }
    //筛选目标用户
        getAuthUserList = (dataSource) => {
            const mockData = [];
            const targetKeys = [];
            if (dataSource && dataSource.length > 0) {
                for (let i = 0; i < dataSource.length; i++) {
                    const data = {
                        key: dataSource[i].user_id,
                        title: dataSource[i].user_name,
                        status: dataSource[i].status,
                    };
                    if (data.status == 1) {
                        //目标用户
                        targetKeys.push(data.key);
                    }
                     mockData.push(data);
                }
            }
            this.setState({
                mockData, 
                targetKeys
            });
        };
    requestList = () => {
        axios.get("https://www.studyinghome.com/mock/5e4ca5d80167590746b7615d/example/perss")
        .then((res) => {
            this.setState({
                dataSource:res.data.list
            })
        })
    }
    render() {
        const columns = [
            {
                title: '角色ID',
                dataIndex: 'id'
            }, {
                title: '角色名称',
                dataIndex: 'role_nam',
            },{
                title: '创建时间',
                dataIndex: 'create_time',
                // render: Utils.formatTime
            }, {
                title: '使用状态',
                dataIndex: 'status',
                render(status){
                    if (status == 1) {
                        return "启用"
                    } else {
                        return "停用"
                    }
                }
            }, {
                title: '授权时间',
                dataIndex: 'authorize_time',
                //  render: Utils.formatTime
            }, {
                title: '授权人',
                dataIndex: 'authorize_user_name',
            }
        ];
        const rowSelection={
            type:"radio",
            selectedRowKeys:this.state.selectedRowKeys
        }
        return (
            <div>
                <Card>
                    <Button type="primary" onClick={this.handleRole} style={{margin:"0 10px"}}>创建角色</Button>
                    <Button type="primary" onClick={this.handlePermission}  style={{margin:"0 10px"}}>权限设置</Button>
                    <Button type="primary" onClick={this.handleUserAuth} style={{margin:"0 10px"}}>用户授权</Button>
                </Card>
                <ETable
                    updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                    selectedRowKeys={this.state.selectedRowKeys}
                    columns={columns}
                    dataSource={this.state.dataSource}
                    selectedRowKeys={this.state.selectedRowKeys}
                />
                <Modal 
                    title="创建角色"
                    visible={this.state.isRoleVisible}
                     onOk={this.handleRoleSubmit}
                    onCancel={()=> {
                         this.roleForm.props.form.resetFields();
                        this.setState({
                            isRoleVisible:false
                        })
                    }}
                >
                    <RoleForm wrappedComponentRef={(inst) => this.roleForm = inst }/>
                   
                </Modal> 
                <Modal
                    title="权限设置"
                    visible={this.state.isPersVisible}
                    width={500}
                    onOk={this.handlePersSubmit}
                    onCancel={() => {
                        this.setState({
                            isPersVisible:false
                        })
                    }}
                >
                    <PermEditForm
                         wrappedComponentRef={(inst) => this.roleForm = inst }
                        detailInfo={this.state.detailInfo}
                        menuInfo={this.state.menuInfo||[]}
                        //回调函数改变默认显示
                        patchMenoInfo={(checkedKeys) => {
                            this.setState({
                                menuInfo:checkedKeys
                            })
                        }}
                    />
                </Modal>
                <Modal
                    title="用户授权"
                    visible={this.state.isUserVisible}
                    width={800}
                    onOk={this.handleUserSubmit}
                    onCancel={()=>{
                        this.setState({
                            isUserVisible:false
                        })
                    }}>
                        <RoleAuthForm 
                                  wrappedComponentRef={(inst) => this.userAuthForm = inst }
                                  isClosed={this.state.isAuthClosed}
                                  detailInfo={this.state.detailInfo}
                                  targetKeys={this.state.targetKeys}
                                  mockData={this.state.mockData}
                                  patchUserInfo={this.patchUserInfo}
                           />
                </Modal>
            </div>
        )
    }
}
// 角色创建
class RoleForm extends React.Component{
   
    render() {
        const { getFieldDecorator} = this.props.form
        const fromList = {
            labelCol:{span: 5},
            wrapperCol:{span: 13}
        }
        return(
           <Form>
               <FormItem label="角色" {...fromList}>
                   {
                       getFieldDecorator("role_name",{

                       })(
                        <Input type="text" placeholder="请输入角色名称"/>
                       )
                   }
               </FormItem>
               <FormItem label="状态" {...fromList}>
                   {
                       getFieldDecorator("state",{
                       })(
                            <Select>
                                <Option value={0}>开启</Option>
                                <Option value={1}>关闭</Option>
                            </Select>
                       )
                   }
               </FormItem>
           </Form>
        )
    }
}
RoleForm = Form.create({})(RoleForm)
class PermEditForm extends React.Component{
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if(item.children) {
                return <TreeNode title={item.title} key={item.key}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            }
            return <TreeNode  title={item.title} key={item.key}>
                {item.title}
            </TreeNode>
        })
    }
    onCheck = (checkedKeys) => {
        this.props.patchMenoInfo(checkedKeys)
    }
    render() {
        const {getFieldDecorator} = this.props.form
         const detail_info = this.props.detailInfo
         const menuInfo = this.props.menuInfo
        // console.log(menuInfo)
       // console.log(this.props.detailInfo)
        const labelList={
            labelCol:{span:4},
            wrapperCol:{span:12}
        }
        return (
            <Form layout="horizontal">
                <FormItem {...labelList}>          
                     <Input disabled placeholder={detail_info.role_nam}/>
                </FormItem>
                <FormItem {...labelList}>
                    {
                        getFieldDecorator("status",{
                            initialValue:1
                        })(
                            <Select>
                                 <Option value={1}>请选择</Option>
                                <Option value={2}>启用</Option>
                                <Option value={3}>禁用</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <Tree
                    
                    checkable//复选框
                    defaultExpandAll//默认展开
                    onCheck={(checkedKeys) => {
                        //发生改变的时候重新存储
                        this.onCheck(checkedKeys)
                    }}
                    //默认显示哪些属性
                    checkedKeys={menuInfo}
                >
                    <TreeNode title="平台权限" key="all">
                        {this.renderTreeNodes(menoConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PermEditForm = Form.create({})(PermEditForm)
// 用户授权
class RoleAuthForm extends React.Component {
    render() {
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 18}
        };
        const detail_info = this.props.detailInfo;
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称：" {...formItemLayout}>
                    <Input disabled maxLength={8} placeholder={detail_info.role_name}/>
                </FormItem>
                <FormItem label="选择用户：" {...formItemLayout}>
                    <Transfer
                        listStyle={{width: 200,height: 400}}
                        dataSource={this.props.mockData}
                        showSearch
                        titles={['待选用户', '已选用户']}
                        searchPlaceholder='输入用户名'
                        filterOption={this.filterOption}
                        targetKeys={this.props.targetKeys}
                        onChange={this.handleChange}
                        render={item => item.title}
                    />
                </FormItem>
            </Form>
        )
    }
}
RoleAuthForm = Form.create({})(RoleAuthForm);